<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8"/>
    <title>复选框</title>
</head>

<body>

<script type="text/javascript">
    window.onload = function() {
        let loves = document.getElementsByName("love");
        let box = document.getElementById("boxid");
        /*if (box.checked === false) {
            for (let i = 0; i < loves.length; i++) {
                loves[i].checked = false;
            }
        } else {
            for (let i = 0; i < loves.length; i++) {
                loves[i].checked = true;
            }
        }*/
        box.onclick = function () {
            for (let i = 0; i < loves.length; i++) {
                loves[i].checked = box.checked;
            }
        }
        //当复选框全部选择时,第一个框 需要被选上
        let all = loves.length;
        for (let i = 0; i < loves.length; i) {
            //遍历复选框, 给每一个都加上 点击事件
            loves[i].onclick = function () {
                let checkedCount = 0;
                // 初始化被选择的记录数
                for (let i = 0; i < loves.length; i++) {
                    if (loves[i].checked) {
                        checkedCount++;
                    }
                }
                box.checked = (all === checkedCount);
            };
        }
    }
</script>

<label for="boxid">全选/全不选</label>
<input type="checkbox" id="boxid" />
<br/>
<label>
    <input type="checkbox" name="love"/>篮球
</label>
<br/>
<label>
    <input type="checkbox" name="love"/>排球
</label>
<br/>
<label>
    <input type="checkbox" name="love"/>羽毛球
</label>
<br/>
<label>
    <input type="checkbox" name="love"/>乒乓球
</label>
<br/>

<input type="button" value="全选" onclick="setAll()"/>
<input type="button" value="全不选" onclick="setNo()"/>
<input type="button" value="反选" onclick="setOthers()"/>


<script type="text/javascript">

    //全选函数
    function setAll() {
        let loves = document.getElementsByName("love");
        for (let i = 0; i < loves.length; i++) {
            loves[i].checked = true;
        }


    }

    //全不选函数
    function setNo() {
        let loves = document.getElementsByName("love");
        for (let i = 0; i < loves.length; i++) {
            loves[i].checked = false;
        }
    }

    //反选
    function setOthers() {
        let loves = document.getElementsByName("love");
        for (let i = 0; i < loves.length; i++) {
             /*if (loves[i].checked === false)
                 loves[i].checked = true;
             else
                 loves[i].checked = false;*/
            loves[i].checked = !loves[i].checked;
        }
    }


    //全选/全不选操作

</script>

</body>

</html>
